<template>
  <div class="app-container" style="height: 100%">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline>
      <el-form-item>
        <header-select @selectProject="onSelectProject" style="line-height: normal" />
      </el-form-item>
      <el-form-item prop="problemId">
        <el-cascader v-model="checkedProblemIds" :options="problemTree" :props="treeProps" clearable placeholder="请选择问题类型" />
      </el-form-item>
      <el-form-item prop="discovererName">
        <el-input v-model.trim="queryParams.discovererName" placeholder="请输入发现人" clearable @keyup.enter.native="handleQuery" style="width: 130px" />
      </el-form-item>
      <!--
      <el-form-item prop="responsibleName">
        <el-input v-model.trim="queryParams.responsibleName" placeholder="请输入责任人" clearable @keyup.enter.native="handleQuery" style="width: 130px" />
      </el-form-item>
      -->
      <el-form-item prop="accepterName">
        <el-input v-model.trim="queryParams.accepterName" placeholder="请输入验收人" clearable @keyup.enter.native="handleQuery" style="width: 130px" />
      </el-form-item>
      <el-form-item prop="inspectionType">
        <el-select v-model="queryParams.inspectionType" placeholder="请选择来源" clearable style="width: 130px">
          <el-option v-for="dict in dict.type.cq_route_inspection_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="seriousLevel">
        <el-select v-model="queryParams.seriousLevel" placeholder="请选择问题等级" clearable style="width: 140px">
          <el-option v-for="dict in dict.type.cq_route_inspection_serious_level" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择问题状态" clearable style="width: 160px">
          <el-option v-for="dict in dict.type.cq_route_inspection_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="beginDate">
        <el-date-picker v-model="queryParams.beginDate" type="date" value-format="yyyy-MM-dd" placeholder="录入时间从" style="width: 130px" @change="dateChanged" />
      </el-form-item>
      <el-form-item prop="endDate">
        <el-date-picker v-model="queryParams.endDate" type="date" value-format="yyyy-MM-dd" placeholder="至" style="width: 130px" @change="dateChanged" />
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="listLoading" :data="list" size="small">
      <el-table-column label="所属项目" prop="projectName" min-width="200" show-overflow-tooltip />
      <el-table-column label="问题来源" align="center">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_route_inspection_type" :value="row.inspectionType" />
      </el-table-column>
      <el-table-column label="问题位置" prop="positionName" min-width="200" show-overflow-tooltip />
      <el-table-column label="问题类型" prop="problemName" min-width="200" show-overflow-tooltip />
      <el-table-column label="问题等级" align="center">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_route_inspection_serious_level" :value="row.seriousLevel" />
      </el-table-column>
      <el-table-column label="发现人" prop="discovererName" width="100" show-overflow-tooltip />
      <el-table-column label="问题录入时间" prop="createTime" width="150px" />
      <el-table-column label="问题状态" min-width="100">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_route_inspection_status" :value="row.status" />
      </el-table-column>
      <!--
      <el-table-column label="责任人" prop="responsibleName" width="80" show-overflow-tooltip />
      <el-table-column label="整改时限" prop="rectificationTimeLimit" align="center" />
      <el-table-column label="整改时间" width="150px">
        <template slot-scope="{ row }">{{ parseTime(row.rectifyFirstTime) }}</template>
      </el-table-column>
      <el-table-column label="验收通过时间" width="150px">
        <template slot-scope="{ row }">{{ parseTime(row.acceptFinalTime) }}</template>
      </el-table-column>
      <el-table-column label="抄送人" prop="ccName" width="80" show-overflow-tooltip />
      <el-table-column label="整改人" prop="rectifierName" width="80" show-overflow-tooltip />
      -->
      <el-table-column label="验收人" prop="accepterName" width="80" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="{ row }" >
          <el-button size="mini" type="text" icon="el-icon-tickets" @click="$refs.ItemInfo.open({ inspectionId: row.inspectionId })">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-document-copy" @click="handleRevokeRouteInspection(row)">撤销</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <ItemInfo ref="ItemInfo" />
  </div>
</template>
<script>
// 日常巡查页面
import moment from 'moment'
import auth from '@/plugins/auth'
import { flatList2tree } from '@/utils'
import { listCheckType, listCheckTable, listCheckSc } from '@/api/qualityManage/cq'
import { listRouteInspection } from '@/api/cq/routeInspection'
import { revokeRouteInspection } from '@/api/cq/routeInspection'
import HeaderSelect from './components/HeaderSelect'
import ItemInfo from './components/DailyInspectionInfo'
export default {
  name: 'DailyInspection',
  dicts: ['cq_route_inspection_type', 'cq_route_inspection_serious_level', 'cq_route_inspection_status'],
  components: { HeaderSelect, ItemInfo },
  data() {
    return {
      listLoading: false,
      total: 0,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: '',
        discovererName: '',
        // responsibleName: '',
        accepterName: '',
        inspectionType: '',
        seriousLevel: '',
        status: '',
        problemId: '',
        beginDate: '',
        endDate: ''
      },
      treeProps: {
        checkStrictly: true,
        leaf: 'isLeaf',
        lazy: true,
        lazyLoad: this.lazyLoadCheckTable
      },
      problemTree: [], // 工序树
      checkedProblemIds: []
    }
  },
  computed: {
    showBtns() {
      // 操作按钮权限
      const permCode = 'cq:patrol:dailyInspection'
      const edit = auth.hasPermi(`${permCode}:edit`)
      const add = auth.hasPermi(`${permCode}:add`)
      const remove = auth.hasPermi(`${permCode}:remove`)
      const info = auth.hasPermi(`${permCode}:info`)
      const enable = auth.hasPermi(`${permCode}:enable`)
      const disable = auth.hasPermi(`${permCode}:disable`)
      return { edit, add, remove, info, enable, disable }
    }
  },
  created() {
    this.getProblemTree()
  },
  methods: {
    onSelectProject(project) {
      const projectId = project?.id || ''
      this.queryParams.projectId = projectId
      if (projectId) this.getList()
    },
    async getList() {
      const { projectId } = this.queryParams
      if (!projectId) {
        this.$message('请选择项目')
        return (this.list = [])
      }

      const opt = { ...this.queryParams }

      // 日期加时间
      if (opt.beginDate) opt.beginDate = `${opt.beginDate} 00:00:00`
      if (opt.endDate) opt.endDate = `${opt.endDate} 23:59:59`

      // 选中的树形问题类型的最后一项
      if (this.checkedProblemIds.length) {
        const ids = this.checkedProblemIds
        const lastId = ids[ids.length - 1] || ''
        if (lastId) opt.problemId = lastId
      }

      this.listLoading = true
      const res = await listRouteInspection(opt).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.rows || []
      data.map(i => {
        i.picList = i.picList || []
      })
      this.list = data
      this.total = res.total || 0
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.checkedProblemIds = []
      this.handleQuery()
    },
    async getProblemTree() {
      const [res1, res2] = await Promise.all([this.getCheckTypeList(), this.getCheckScList()])
      this.problemTree = [
        { label: '关键工序', value: 'gjgx', type: 'KP', disabled: true, children: res1 },
        { label: '安全文明', value: 'aqwm', type: 'SC', disabled: true, children: res2 }
      ]
    },
    async getCheckTypeList() {
      const res = await listCheckType().catch(() => false)
      if (res === false) return []

      const data = res.data || []
      data.map(i => {
        i.type = 'checkType'
        i.label = i.typeName
        i.value = i.typeId
      })
      return data
    },
    async getCheckScList() {
      const res = await listCheckSc().catch(() => false)
      if (res === false) return []

      let data = res.data || []
      data.map(i => {
        i.type = 'checkSc'
        i.label = i.scName
        i.value = i.scId
      })
      data = flatList2tree(data, { id: 'scId' })
      return data
    },
    async lazyLoadCheckTable(node, resolve) {
      if (node?.data?.type !== 'checkType') return resolve([])

      const res = await listCheckTable({ typeId: node.data.typeId }).catch(() => false)
      if (res === false) return resolve([])

      let data = res.data || []
      data.map(i => {
        i.type = 'checkTable'
        i.label = i.tableName
        i.value = i.tableId
      })
      data = flatList2tree(data, { id: 'tableId' })
      resolve(data)
    },
    /** 撤销按钮操作 */
    async handleRevokeRouteInspection(row) {
      const inspectionId = row.inspectionId;
      const res1 = await this.$confirm(`是否要撤销当前问题?`, '警告', {type: 'warning'}).catch(() => false);
      if (res1 !== 'confirm') return;

      const res = await revokeRouteInspection({inspectionId}).catch(() => false);
      if (res === false) return;

      this.msgSuccess('操作成功');
      this.handleQuery();
    },
    dateChanged() {
      const { beginDate, endDate } = this.queryParams
      if (beginDate && endDate && moment(beginDate).isAfter(moment(endDate))) {
        this.$message.info('录入结束时间不能小于开始时间')
        this.queryParams.endDate = ''
      }
    }
  }
}
</script>
<style lang="scss" scoped>
// multi-select tags
.select-type /deep/ .el-select__tags {
  > span {
    display: flex;
    width: 100%;
  }
  .el-tag:first-child {
    overflow: hidden;
  }
}
</style>
